#!/bin/sh

# Copyright © 2013 Alex Kost

# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.

# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.

# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

#### HELP MESSAGE ##############################################
hlp='Usage: ln-dir SOURCE DESTINATION
Make "hard link to a directory", i.e. create a whole directory structure
for SOURCE dir in DESTINATION dir and make hard links for all files in
new directories.'

if [ "$1" = "-h" ] || [ "$1" = "--help" ]; then
    echo "$hlp"
    exit 0
fi
################################################################

Dir_Check()
{
    if [ ! -d "$1" ]; then
        echo "$1 - is not a directory"
        exit 1
    fi
}

Dir_Check "$1"
Dir_Check "$2"

# set source and destination vars and move to source dir
dest=$(cd "$2"; pwd)
cd "$1"
source=$(pwd)

echo "HARDLINKING \"$source\" INTO \"$dest\""
dest=$dest/$(basename "$source")

echo -e "\n---- Making directory structure"
mkdir -v "$dest"
find . -mindepth 1 -type d | xargs -I === mkdir -v "$dest/==="

echo -e "\n---- Making hard links"
find . -type d | \
while read dir; do
    ln -v "$dir"/* "$dest/$dir" 2> /dev/null
done
